const fs = require('fs').promises;
const path = require('path');
const schedule = require('node-schedule');

class BackupService {
    constructor(dataDir, backupDir = 'backups') {
        this.dataDir = dataDir;
        this.backupDir = backupDir;
        this.init();
    }

    async init() {
        try {
            await fs.mkdir(this.backupDir, { recursive: true });
        } catch (error) {
            console.error('创建备份目录失败:', error);
        }
    }

    async createBackup() {
        try {
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const backupPath = path.join(this.backupDir, `backup-${timestamp}.json`);
            
            await fs.copyFile(
                path.join(this.dataDir, 'ip_records.json'),
                backupPath
            );
            
            console.log(`[${new Date().toISOString()}] 数据已备份`);
            await this.cleanOldBackups();
        } catch (error) {
            console.error('备份失败:', error);
        }
    }

    async cleanOldBackups() {
        try {
            const files = await fs.readdir(this.backupDir);
            const backups = files.filter(f => f.startsWith('backup-'))
                                .sort()
                                .reverse();
            
            // 删除旧备份
            if (backups.length > 10) {
                for (const file of backups.slice(10)) {
                    await fs.unlink(path.join(this.backupDir, file));
                }
            }
        } catch (error) {
            console.error('清理旧备份失败:', error);
        }
    }

    // 启动定时备份（每天凌晨3点）
    startScheduledBackup() {
        schedule.scheduleJob('0 3 * * *', () => {
            this.createBackup();
        });
        console.log('已启动定时备份任务');
    }
}

module.exports = { BackupService }; 